// import { login, logout, getUserInfo } from '@/api/login'
import { getTokenByAuthCode, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      organizationName: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      getTokenByAuthCode(params) {
        return new Promise((resolve, reject) => {
          getTokenByAuthCode(params).then(response => {
            if (response.code === 1) {
              setToken(response.data.accessToken.tokenValue)
              this.token = response.data.accessToken.tokenValue
              resolve(response)
            } else {
              reject(response.message)
            }
          }).catch(error => {
            // http请求异常
            reject(error.message || '登录接口异常，请联系管理员！')
          })
        })
      },

      // 获取用户信息
      getUserInfo() {
        return new Promise((resolve, reject) => {
          getUserInfo().then(res => {
            const userInfo = res.data
            // const user = res.user
            // const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;
            // if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            //   this.roles = res.roles
            //   this.permissions = res.permissions
            // } else {
            //   this.roles = ['ROLE_DEFAULT']
            // }
            this.id = userInfo.userId
            this.name = userInfo.name
            this.avatar = userInfo.avatarUrl
            this.organizationName = userInfo.organizationName
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },

      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          this.token = ''
          this.roles = []
          this.permissions = []
          removeToken()
          resolve()
          // logout(this.token).then(() => {
          //   this.token = ''
          //   this.roles = []
          //   this.permissions = []
          //   removeToken()
          //   resolve()
          // }).catch(error => {
          //   reject(error)
          // })
        })
      }
    }
  })

export default useUserStore
